package com.ChefApp.mobile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Receipe extends Activity{
	//Variablen
	String url,zubereitungText,zutatenText,titleText,portion1,userName,value,subTitle;
	String[] fileList;
	String datum,grad,Brenn,zeit,type,bewFile;
	ProgressDialog loadReceipePD;
	Document rezeptSeite;
	
	Zutaten zuClass;
	TextView tvZutaten,	tvTitle, tvZubereitung,	tvSubTitle,tvBrenn,tvzeit,tvgrad,tvdatum; 
	ImageView ivRec,ivWertung;
	Bitmap bild,wertung;
	Button umrechnen;
	EditText umrET;
	
	 static final int NUMBER_DIALOG_ID = 0;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle cicle = getIntent().getExtras();
		url=cicle.getString("url");
		subTitle="Kein Untertitel";
		type = cicle.getString("type");
		if (type.equals("list")) {
					subTitle=cicle.getString("subtitle");

		}
		bild=Bitmap.createScaledBitmap((Bitmap) cicle.get( "image"), 230, 164,false);
        setContentView(R.layout.receipe);
        new TheTask().execute();
        tvZutaten= (TextView) findViewById(R.id.textViewrecZutaten1);
 		tvTitle = (TextView) findViewById(R.id.textViewrec1);
 		tvSubTitle = (TextView) findViewById(R.id.textViewrec2);
 		ivWertung = (ImageView) findViewById(R.id.imageViewWertung2);
 		ivRec=(ImageView) findViewById(R.id.imageViewrec1);
 		umrET=(EditText) findViewById(R.id.editTextrec1); 
 		tvZubereitung =(TextView) findViewById(R.id.textViewrecZubereitung1);
        umrechnen = (Button) findViewById(R.id.buttonrec1);
        tvBrenn = (TextView) findViewById(R.id.textViewBrenn);
        tvzeit = (TextView) findViewById(R.id.textViewzeit);
        tvgrad = (TextView) findViewById(R.id.textViewgrad);
        tvdatum = (TextView) findViewById(R.id.textViewDate);
        tvSubTitle = (TextView) findViewById(R.id.textViewrec2);
       };
       
       @Override
   	public boolean onCreateOptionsMenu(Menu menu) {
   	    MenuInflater inflater = getMenuInflater();
   	    inflater.inflate(R.menu.rec_menu, menu);
   	    return true;
   	}
   	
       
   	@Override
   	public boolean onOptionsItemSelected(MenuItem item) {
   	    // Handle item selection
   	    switch (item.getItemId()) {
   	    case R.id.save:
   	    	getUserName();
   	        
   	        
   	        return true;
   	    case R.id.open:
   		 Intent arch_intent = new Intent();
   		 arch_intent.setClass(Receipe.this, OpenArchiv.class);
   		 startActivity(arch_intent);
	        
	        return true;
   	    /*case R.id.help:
   	        showHelp();
   	        return true;*/
   	    default:
   	        return super.onOptionsItemSelected(item);
   	    }
   	}
    private void getUserName() {
		// TODO Auto-generated method stub
		final AlertDialog.Builder alert = new AlertDialog.Builder(this);
		final EditText input = new EditText(this);
		alert.setView(input);
		alert.setTitle("Wählen sie einen Namen für das Rezept");
		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				userName = input.getText().toString().trim();
				if (userName.equals("")) {userName ="Rezept";}
				saveReceipe();
			}
		});

		alert.setNegativeButton("Abbrechen",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.cancel();
						
					}
				});
		alert.show();
		
	}
	private class TheTask extends AsyncTask<Void, Void, Void> {
    	@Override
        protected void onPreExecute() {
            loadReceipePD = ProgressDialog.show(Receipe.this, "", "Laden...", true, false);
        }

        @Override
        protected Void doInBackground(Void... params) {
        	try {
				rezeptSeite = Jsoup.connect(url).userAgent("Mozilla").get();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}   
			Element zutaten = rezeptSeite.getElementById("rezept-zutaten");
			Element zubereitung = rezeptSeite.getElementById("rezept-zubereitung");
			Element infos = rezeptSeite.getElementById("rezept-infos");
			//Elements kommentare = rezeptSeite.getElementsByClass("comment-body-inner");
			Elements h1 =rezeptSeite.getElementsByTag("h1");
			Element title = h1.get(1);
			Elements portion = rezeptSeite.getElementsByAttributeValue("name", "divisor");
			Element portionen=portion.first();
			Elements info =infos.getElementsByTag("tr");
			
			datum = info.get(4).text();
			zeit = info.get(1).text();
			grad = info.get(2).text();
			Brenn = info.get(3).text();
			String bewertungUrl = rezeptSeite.getElementById("rezept-score-img").attr("src");
			int length = bewertungUrl.length();
			String score = "5";
			if( bewertungUrl.matches(".*\\d_\\d.*")) {
				
				score = bewertungUrl.substring(length-7, length-4);
			} else if (bewertungUrl.matches(".*\\d.*")) {
				score =bewertungUrl.substring(length-5,length-4);
			}
			
			bewFile = "score"+score;
			
			Log.v("wertung", bewertungUrl);
			try {
				wertung = Bitmap.createScaledBitmap(MyImageLoader.LoadImage(bewertungUrl), 115, 30,false);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (portionen != null) {
				portion1 = portionen.attr("value");
			}
			titleText=checker(title);
			if (zutaten != null){
				zuClass = new Zutaten(zutaten);
			}
			if (zuClass != null){
				zutatenText = zuClass.getText();
			}
			
			zubereitungText = checker(zubereitung);
			
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
        	loadReceipePD.dismiss();
        	
            tvZutaten.setText(zutatenText);
			tvTitle.setText(titleText);
		 	
			
			if (bild!=null) {
				ivRec.setImageBitmap(bild);
			}
			umrET.setText(portion1);
            tvZubereitung.setText(zubereitungText); 
            tvBrenn.setText(Brenn);
            tvgrad.setText(grad);
            tvdatum.setText(datum);
            tvzeit.setText(zeit);
            ivWertung.setImageBitmap(wertung);
            tvSubTitle.setText(subTitle);
            
            if (type.equals("daily")) {
            	tvSubTitle.setHeight(0);
            	tvSubTitle.setVisibility(View.GONE);
            }
            
            umrechnen.setOnClickListener(new View.OnClickListener() {
    			
            	
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    				if (umrET.getText().toString().matches("\\d*")){
    				String neueZutaten = zuClass.umrechnen(portion1, umrET.getText().toString());
    				tvZutaten.setText(neueZutaten);
    				} else {
    					Toast.makeText(getApplicationContext(), "Kein g�ltiger Wert!!!", Toast.LENGTH_LONG).show();
    				}
    			}
    		});
           
        }
    }
    
public String checker(Element e) {
	if (e != null){
		return e.text();
	} else {
		return "empty";
	}
}


private void saveReceipe() {
	// TODO Auto-generated method stub
	
	String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
	File dir = new File(extStorageDirectory +"/ChefKochApp/Receipes/");
	fileList = dir.list(new FilenameFilter() {
	    public boolean accept(File d, String name) {
	       return name.endsWith(".jpg");
	    }
	});
	int id = 0;
	if (fileList!=null) {
		id=fileList.length;
	}
	String xmlrec = writeXml(id);
	
	
	
	 OutputStream outStream = null;
	   File dire = new File(extStorageDirectory,"/ChefKochApp/Receipes");
	   dire.mkdirs();
	   File file = new File(extStorageDirectory, "/ChefKochApp/Receipes/Receipe"+id+".xml");
	   File bmFile =new File(extStorageDirectory, "/ChefKochApp/Receipes/Receipe"+id+ ".jpg");
	   
	   try {
		   OutputStream imageOut = new FileOutputStream(bmFile);
		   bild.compress(Bitmap.CompressFormat.JPEG, 85, imageOut);
	      
		   
		   outStream = new FileOutputStream(file, true);
	   
	   ObjectOutputStream ooutstream = new ObjectOutputStream(outStream);
	    ooutstream.writeObject(xmlrec);
	    ooutstream.flush();
	    ooutstream.close();
	    outStream.flush();
	    outStream.close();
		imageOut.flush();
		imageOut.close();

	   
	    Toast.makeText(Receipe.this, userName+" gespeichert", Toast.LENGTH_LONG).show();
	   
	   } catch (FileNotFoundException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	    Toast.makeText(Receipe.this, e.toString(), Toast.LENGTH_LONG).show();
	   } catch (IOException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	    Toast.makeText(Receipe.this, e.toString(), Toast.LENGTH_LONG).show();
	   }
}






private String writeXml(int id){
   
    String firstTry="";
       
			
			firstTry="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n ";
		Log.v("username", userName);
        
        firstTry= firstTry+"<Receipe id=\""+id+"\">\n" +
        		"<title>"+titleText+"</title>\n" +
        		"<subtitle>"+subTitle+"</subtitle>"+
        		"<category>"+""+"</category>\n"+
        		"<uName>"+ userName + "</uName>\n"+
        		"<portionen>"+portion1+"</portionen>\n" +
        		"<url>" + url + "</url>\n" +
        		"<zutatenText>"+zutatenText+"</zutatenText>\n" +
        		"<brennwert>"+Brenn+"</brennwert>"+
        		"<grad>"+grad+"</grad>"+
        		"<zeit>"+zeit+"</zeit>"+
        		"<datum>"+datum+"</datum>"+
        		"<bewertung>"+bewFile+"</bewertung>";
        		
        firstTry=firstTry+"<zutaten>\n";
        int zuID=0;
        for (String zutat : zuClass.zutatenContainer){
        	String anzahl = zuClass.anzahlContainer.elementAt(zuID).toString();
        	String einheit = zuClass.einheiten.elementAt(zuID);
        	firstTry = firstTry + "<zutat id =\""+zuID+"\">\n" + "<anzahl>"+anzahl+"</anzahl>\n" +
        	"<einheit>"+einheit+"</einheit>\n"+"<name>"+zutat+"</name>\n </zutat>\n";
        	zuID++;
        }
        		
        		
        		
        		
        		
        firstTry= firstTry+"</zutaten>\n"+"<zubereitung>"+zubereitungText+"</zubereitung>\n"+
        		"</Receipe>\n";
        	
        	
        return firstTry;
   
}

}